package pers.xuehongyan.useat.server.utils;

import java.util.BitSet;
import java.util.HashMap;

/**
 * @author xuehongyan
 */
public class GeoHash {
    static final int NUM_BITS = 6 * 5;
    static final int BASE = 32;
    final static char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'b', 'c', 'd', 'e', 'f', 'g',
            'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r',
            's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    final static HashMap<Character, Integer> LOOKUP = new HashMap<>();

    static {
        int i = 0;
        for (char c : DIGITS) {
            LOOKUP.put(c, i++);
        }
    }

    public String encode(double lat, double lng, int len) {
        return encode(lat, lng).substring(0, len);
    }

    private String encode(double lat, double lon) {
        BitSet latBits = getBits(lat, -90, 90);
        BitSet lngBits = getBits(lon, -180, 180);
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < NUM_BITS; i++) {
            buffer.append(lngBits.get(i) ? '1' : '0');
            buffer.append(latBits.get(i) ? '1' : '0');
        }
        return base32(Long.parseLong(buffer.toString(), 2));
    }

    private BitSet getBits(double d, double floor, double ceiling) {
        BitSet buffer = new BitSet(NUM_BITS);
        for (int i = 0; i < NUM_BITS; i++) {
            double mid = (floor + ceiling) / 2;
            if (d >= mid) {
                buffer.set(i);
                floor = mid;
            } else {
                ceiling = mid;
            }
        }
        return buffer;
    }

    private static String base32(long i) {
        char[] buf = new char[BASE * 2 + 1];
        int charPos = BASE * 2;
        boolean negative = (i < 0);
        if (!negative) {
            i = -i;
        }
        while (i <= -BASE) {
            buf[charPos--] = DIGITS[(int) (-(i % BASE))];
            i /= BASE;
        }
        buf[charPos] = DIGITS[(int) (-i)];

        if (negative) {
            buf[--charPos] = '-';
        }
        return new String(buf, charPos, (65 - charPos));
    }
}